function fun(str) {
    let n = str.length;
    let ans = '';
    let j = 0;
    for(let i = 0; i < n;) {
        let num = 0;
        while(j < n && str[j]==str[i]) {
            j++;
            num++;
        }
        ans = ans+num+str[i]
        i = j;
    }
    return ans;
}
console.log(fun('aaabbcaa'))